/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-07-27
 * Time: 9:17
 */
public class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int result = 0;
        int max = 0;
        for (int x: piles) {
            max = Math.max(max, x);
        }
        int left = 1;
        int right = max;
        while (left <= right) {
            // 注意加上括号, 因为 >> 的优先级比较低
            int mid = ((right - left) >> 1) + left;
            // 注意 time 的类型为 long , 不然会越界
            long time = getTime(piles, mid);
            if (time <= h) {
                // 更新最接近的值
                result = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return result;
    }

    private long getTime(int[] piles, int speed) {
        long time = 0;
        for (int x: piles) {
            time += (x-1)/speed + 1;
        }
        return time;
    }
}
